<template>
  <div>
    <el-card shadow="never" class="border-0">
      <div class="flex mb-4">
        <el-button type="primary" @click="easyExcelDownload">
          <el-icon class="mr-1">
            <Download/>
          </el-icon>
          下载模板
        </el-button>
        <el-button type="primary" @click="dialogVisible = true">
          <el-icon class="mr-1">
            <Upload/>
          </el-icon>
          导入
        </el-button>
        <el-button type="primary" @click="easyExcelExport">
          <el-icon class="mr-1">
            <Download/>
          </el-icon>
          导出
        </el-button>
      </div>
      <el-table :data="tableData" border max-height="500" style="width: 100%">
        <el-table-column prop="name" label="学生名称" width="180"/>
        <el-table-column prop="studentNum" label="学号" width="180"/>
        <el-table-column prop="age" label="年龄"/>
        <el-table-column prop="sex" label="性别"/>
        <el-table-column prop="birthday" label="出生日期"/>
      </el-table>

      <div class="mt-3">
        <el-pagination
          :current-page="pages.pageNo"
          :page-size="pages.pageSize"
          :page-sizes="[30, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pages.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <el-dialog
        title="导入"
        v-model="dialogVisible"
        :open="openDialog"
        width="30%">
        <el-upload
          class="pt-5"
          ref="formRef"
          action="#"
          accept=".xlsx,.xls"
          :auto-upload="false"
          :file-list="fileList"
          :http-request="handleFileSuccess"
          :on-change="handlerFileChange"
          :limit="1"
        >
          <el-button :icon="Upload" type="primary"
          >选择文件
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
            </div>
          </template>
        </el-upload>
        <div class="mt-10">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="importButtonLoading">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {easyExcelDownloadApi, easyExcelExportApi, easyExcelImportFileApi} from "@/api/easyExcel.js";
import {Upload} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {studentPageList} from "@/api/student.js";

onMounted(() => {
  tableDataLoad()
})

const tableData = ref([])
const pages = reactive({
  pageNo: 1,
  pageSize: 30,
  total: 0
})
// 列表查询
const tableDataLoad = () => {
  studentPageList({
    pageNo: pages.pageNo,
    pageSize: pages.pageSize
  }).then(resp => {
    if (resp.result) {
      tableData.value = resp.data.list
      pages.total = resp.data.totalNum
    }
  })
}
const handleSizeChange = (value) => {
  pages.pageSize = value
  tableDataLoad()
}

const handleCurrentChange = (value) => {
  pages.pageNo = value
  tableDataLoad()
}


// 下载模板
const easyExcelDownload = () => {
  easyExcelDownloadApi()
    .then(resp => {
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(new Blob([resp], {type: 'application/vnd.ms-excel'}))
      downloadElement.href = href
      downloadElement.download = '学生信息.xls'
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    })
}

// 导出
const easyExcelExport = () => {
  easyExcelExportApi()
    .then(resp => {
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(new Blob([resp]))
      downloadElement.href = href
      downloadElement.download = 'easyExcel导出.csv'
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    })
}

const dialogVisible = ref(false);
const importButtonLoading = ref(false);
const formRef = ref();
const fileList = ref();

const openDialog = () => {
  importButtonLoading.value = false;
  formRef.value.clearFiles();
}
const handlerFileChange = (file, fileListVal) => {
  fileList.value = fileListVal;
};

/** 文件上传成功处理 */
const handleFileSuccess = async data => {
  const formData = new FormData();
  formData.append("file", data.file);
  await easyExcelImportFileApi(formData).then(resp => {
    if (resp.result) {
      ElMessage.success(resp.msg)
      dialogVisible.value = false
    } else {
      ElMessage.error(resp.msg)
    }
    importButtonLoading.value = false
  }).catch(err => {
    ElMessage.error(err.msg)
  });
};

const onSubmit = () => {
  if (!fileList.value || fileList.value.length === 0) {
    ElMessage({
      message: "请选择文件",
      type: "error"
    });
    return;
  }
  importButtonLoading.value = true
  formRef.value.submit();
};

</script>

<style scoped>

</style>